package com.huawei.struts.exception;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.util.ModuleException;


public class SystemExceptionHandler extends ExceptionHandler {
	@Override
	 
	public ActionForward execute(Exception ex, ExceptionConfig ae,
	         ActionMapping mapping, ActionForm formInstance,
	         HttpServletRequest request, HttpServletResponse response)
	         throws ServletException {

	         ActionForward forward;
	         ActionMessage error;
	         String property;

	         // Build the forward from the exception mapping if it exists
	         // or from the form input
	         if (ae.getPath() != null) {
	             forward = new ActionForward(ae.getPath());
	         } else {
	             forward = mapping.getInputForward();
	         }

	         // Figure out the error
	         if (ex instanceof ModuleException) {
	             error = ((ModuleException) ex).getActionMessage();
	             property = ((ModuleException) ex).getProperty();
	         } else {
	        	 SystemException ece = (SystemException)ex;
	          String errorCode = ece.getErrorCode();
	          Object[] args = ece.getArgs();
	             error = new ActionMessage(errorCode, args);
	             property = error.getKey();
	         }

	         this.logException(ex);

	         // Store the exception
	         request.setAttribute(Globals.EXCEPTION_KEY, ex);
	         this.storeException(request, property, error, forward, ae.getScope());

	         return forward;

	     }



}
